<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <!-- 兼容性视图 -->
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <meta content="更方便快捷搜索，从而达到事半功倍的效果" name="description">
  <title>search you want</title>
  <style>
    html {
      height: 100%;
    }

    body {
      background: #f0f3ef;
      height: 100%;
    }

    .container {
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
    }

    .bgDiv {
      box-sizing: border-box;
      width: 595px;
      height: 55px;
      position: relative;
    /* position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%); */
    }

    .search-input-text {
      border: 1px solid #b6b6b6;
      width: 495px;
      background: #fff;
      height: 33px;
      line-height: 33px;
      font-size: 18px;
      padding: 3px 0 0 7px;
    }

    .search-input-button {
      width: 90px;
      height: 38px;
      color: #fff;
      font-size: 16px;
      letter-spacing: 3px;
      background: #3385ff;
      border: .5px solid #2d78f4;
      margin-left: -5px;
      vertical-align: top;
      opacity: .9;
    }

    .search-input-button:hover {
      opacity: 1;
      box-shadow: 0 1px 1px #333;
      cursor: pointer;
    }

    .suggest {
      width: 502px;
      position: absolute;
      top: 38px;
      border: 1px solid #999;
      background: #fff;
      display: none;
    }

    .suggest ul {
      list-style: none;
      margin: 0;
      padding: 0;
    }

    .suggest ul li {
      padding: 3px;
      font-size: 17px;
      line-height: 25px;
      cursor: pointer;
    }

    .suggest ul li:hover {
      background-color: #e5e5e5
    }
  </style>
</head>

<body>
  <div class="container">
    <div class="bgDiv">
      <input type="text" class="search-input-text" value="" autofocus placeholder="关键词">
      <input type="button" value="搜索一下" class="search-input-button" id="btn">
      <div class="suggest">
        <ul id="search-result">
        </ul>
      </div>
    </div>
  </div>

  <script>
    var suggestContainer = document.getElementsByClassName("suggest")[0];
    var searchInput = document.getElementsByClassName("search-input-text")[0];
    var bgDiv = document.getElementsByClassName("bgDiv")[0];
    var searchResult = document.getElementById("search-result");

    // 清除建议框内容
    function clearContent() {
      var size = searchResult.childNodes.length;
      for (var i = size - 1; i >= 0; i--) {
        searchResult.removeChild(searchResult.childNodes[i]);
      }
    };

    var timer = null;
    // 注册输入框键盘抬起事件
    searchInput.onkeyup = function (e) {
      suggestContainer.style.display = "block";
      // 如果输入框内容为空 清除内容且无需跨域请求
      if (this.value.length === 0) {
        clearContent();
        return;
      }
      if (this.timer) {
        clearTimeout(this.timer);
      }
      if (e.keyCode !== 40 && e.keyCode !== 38) {
        // 函数节流优化
        this.timer = setTimeout(() => {
          // 创建script标签JSONP跨域
          var script = document.createElement("script");
          script.src = "https://www.baidu.com/su?&wd=" + encodeURI(this.value.trim()) +
            "&p=3&cb=handleSuggestion";
          document.body.appendChild(script);
        }, 130)
      }

    };

    // 回调函数处理返回值
    function handleSuggestion(res) {
      // 清空之前的数据！！
      clearContent();
      var result = res.s;
      // 截取前五个搜索建议项
      if (result.length > 4) {
        result = result.slice(0, 5)
      }
      for (let i = 0; i < result.length; i++) {
        // 动态创建li标签
        var liObj = document.createElement("li");
        liObj.innerHTML = result[i];
        searchResult.appendChild(liObj);
      }
      // 自执行匿名函数--删除用于跨域的script标签
      (function () {
        var s = document.querySelectorAll('script');
        for (var i = 1, len = s.length; i < len; i++) {
          document.body.removeChild(s[i]);
        }
      })()
    }


    function jumpPage() {
      window.open(`https://www.baidu.com/s?word=${encodeURI(searchInput.value)}`);
    }

    // 事件委托 点击li标签或者点击搜索按钮跳转到百度搜索页面
    bgDiv.addEventListener("click", function (e) {
      if (e.target.nodeName.toLowerCase() === 'li') {
        var keywords = e.target.innerText;
        searchInput.value = keywords;
        jumpPage();
      } else if (e.target.id === 'btn') {
        jumpPage();
      }
    }, false);

    var i = 0;
    var flag = 1;

    // 事件委托 监听键盘事件
    bgDiv.addEventListener("keydown", function (e) {
      var size = searchResult.childNodes.length;
      if (e.keyCode === 13) {
        jumpPage();
      };
      // 键盘向下事件
      if (e.keyCode === 40) {
        if (flag === 0) {
          i = i + 2;
        }
        flag = 1;
        e.preventDefault();
        if (i >= size) {
          i = 0;
        }
        if (i < size) {
          searchInput.value = searchResult.childNodes[i++].innerText;
        }
      };
      // 键盘向上事件
      if (e.keyCode === 38) {
        if (flag === 1) {
          i = i - 2;
        }
        flag = 0;
        e.preventDefault();
        if (i < 0) {
          i = size - 1;
        }
        if (i > -1) {
          searchInput.value = searchResult.childNodes[i--].innerText;
        }
      };
    }, false);

    // 点击页面任何其他地方 搜索结果框消失
    document.onclick = () => clearContent()
  </script>
</body>

</html>
